package com.dz.wx.controller;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.dz.wx.config.WxConfigProperties;
import com.google.common.collect.ImmutableMap;

@RestController
@Slf4j
public class UploadController extends BaseController {

	@Autowired
	private WxConfigProperties configProperties;

	/**
	 * 上传文件
	 * 
	 * @param file
	 * @return
	 */
	@PostMapping("/wx/upload")
	public Map<String, Object> uploadImage(@RequestParam("file") MultipartFile file) {
		if (null == file) {
			return rtnParam(40010, null);
		}
		String random = RandomStringUtils.randomAlphabetic(16);
		String fileName = random + ".jpg";
		String imgLocalPath = configProperties.getLocalPath();
		String imgHost = configProperties.getImageHost();
		try {
			FileCopyUtils.copy(file.getBytes(), new File(imgLocalPath + "/", fileName));
			return rtnParam(0, ImmutableMap.of("url", imgHost + "/" + fileName));
		} catch (IOException e) {
			log.error("上传文件失败", e);
		}
		return rtnParam(40011, null);
	}
}
